package com.gongj.shej.代理模式;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @program: shej
 * @description:Cglib动态代理
 * @author: gongj
 * @Description: TODO
 * @create: 2020-07-23 14:55
 **/
public class CglibProxy implements MethodInterceptor {

    private Object target;

    public CglibProxy(Object target) {
        this.target = target;
    }
    //给目标对象创建一个代理对象
    public Object getProxyInstance(){
        //1.工具类
        Enhancer en = new Enhancer();
        //2.设置父类
        en.setSuperclass(target.getClass());
        //3.设置回调函数
        en.setCallback(this);
        //4.创建子类(代理对象)
        return en.create();
    }

    private void before() {
        System.out.println("婚庆公司布置结婚现场===");
    }

    /**
     * 后处理
     */
    private void after() {
        System.out.println("婚庆公司打扫结婚现场===");
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        this.before();
        Object invoke = method.invoke(target, objects);
        this.after();
        return invoke;
    }

    public static void main(String[] args) {
        Marry3 me3 = new Me3();
        System.out.println(me3.getClass());
        Me3 me3cglibProxy = (Me3)new CglibProxy(me3).getProxyInstance();
        System.out.println(me3cglibProxy.getClass());

        me3cglibProxy.happrMarry();
    }
}


//结婚
interface Marry3 {
    void happrMarry();
}

//我
class Me3 implements Marry3{

    @Override
    public void happrMarry() {
        System.out.println("我要结婚啦，好开心阿");
    }
}